﻿using Dapper;
using JMS;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ProductServiceHost.Models;
using Serilog;
using System;
using System.Threading;

namespace ProductServiceHost
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            Global.Configuration = builder.Build();

            var port = Global.Configuration.GetValue<int>("Port"); //提供微服务的端口
            var serviceAddress = Global.Configuration.GetValue<string>("ServiceAddress");

            //网关地址
            Global.GatewayAddresses = Global.Configuration.GetSection("Gateways").Get<NetAddress[]>();

            ServiceCollection services = InitServices();

            var msp = new MicroServiceHost(services);
            if (string.IsNullOrEmpty(serviceAddress) == false)
            {
                //自定义微服务地址
                msp.ServiceAddress = new NetAddress(serviceAddress, port);
            }
            
            msp.Register<Controllers.DemoController>("ProductService", "产品服务", false);
            msp.ServiceProviderBuilded += Msp_ServiceProviderBuilded;
            msp.Build(port, Global.GatewayAddresses)
                .Run();
        }

        public static ServiceCollection InitServices()
        {
            ServiceCollection services = new ServiceCollection();
            services.AddSingleton<IConfiguration>(Global.Configuration);
            services.AddScoped<SystemDBContext>();

            //使用Serilog处理日志
            Global.InitSerilogLog();
            services.AddLogging(builder =>
            {
                builder.AddSerilog();
            });

            return services;
        }
        private static void Msp_ServiceProviderBuilded(object sender, IServiceProvider e)
        {
            Global.ServiceProvider = e;

            //修正产品的剩余数量
            using var db = new SystemDBContext();

            var products = db.Connection.Query<Product>("select * from Product where Quantity>0");
            foreach (var product in products)
            {
                //计算已经下单的总数量
                var buyQuantity = db.Connection.ExecuteScalar<int?>("select sum(Quantity) from [Order] where ProductId=@ProductId and PromotionId=@PromotionId", new
                {
                    ProductId = product.Id,
                    PromotionId = product.PromotionId
                });

                if ( buyQuantity.GetValueOrDefault() + product.Quantity != product.TotalQuantity )
                {
                    db.Connection.Execute("update Product set Quantity=@Quantity where Id=@Id",new { 
                        Id = product.Id,
                        Quantity = product.TotalQuantity - buyQuantity
                    });
                }
                    
            }
        }
    }
}
